package com.example.gokuplayalong.service.home;


import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.custom.textwatcher.CustomLimitInputTextWatcher;
import com.example.gokuplayalong.bases.custom.textwatcher.RegExUtil;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.network.security.MD5Keys;
import com.example.gokuplayalong.bases.network.security.MD5Util;
import com.example.gokuplayalong.bases.tools.CaptchaTimer;
import com.example.gokuplayalong.bases.tools.KeyboardsUtils;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.main.UserMainProfile;
import com.example.gokuplayalong.service.fragmentsmanage.BaseFragment;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.huawei.hms.ads.App;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.dialogs.WaitDialog;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.util.Base64;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

import cn.smssdk.SMSSDK;
import me.jessyan.autosize.internal.CancelAdapt;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeLogin#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeLogin extends BaseFragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    View rootView;
    private CardView mHomeLoginPage1;
    private EditText mHomeLoginPage1Phone;
    private Button mHomeLoginPage1GetCaptcha;
    private TextView mHomeLoginPage1PhoneNouse;
    private CheckBox mHomeLoginPage1Checkbox;
    private TextView mHomeLoginPage1Protocol;
    private TextView mHomeLoginPage1Policy;
    private CardView mHomeLoginPage2;
    ImageView mHomeLoginPage2Iv;
    private EditText mHomeLoginPage2Captcha;
    private TextView mHomeLoginPage2CaptchaGetCaptchaNew;
    private LinearLayout mHomeLoginPage3;
    private ImageView mHomeLoginPage3Iv;
    private RadioGroup mHomeLoginPage3RadioGroup;
    private RadioButton mHomeLoginPage3RadioGroupBtn1;
    private RadioButton mHomeLoginPage3RadioGroupBtn2;
    private LinearLayout mHomeLoginPage3WaySelect;
    private LinearLayout mHomeLoginPage3Way1;
    private TextView mHomeLoginPage3Way1Question;
    private EditText mHomeLoginPage3Way1Answer;
    private LinearLayout mHomeLoginPage3Way2;
    private EditText mHomeLoginPage3WayCardNo;
    private EditText mHomeLoginPage3OriginPhone;
    private EditText mHomeLoginPage3Phone;
    private EditText mHomeLoginPage3Captcha;
    private Button mHomeLoginPage3GetCaptcha;
    private Button mHomeLoginPage3Submit;
    Timer timer;
    int verifyWay = 0;

    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1: {
                    try {
                        PopTip.show("获取验证码成功!");
                        CaptchaTimer.captchaTime = 60;
                        mHomeLoginPage1.setVisibility(View.GONE);
                        mHomeLoginPage2.setVisibility(View.VISIBLE);
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
                case 2: {
                    try {
                        PopTip.show("验证成功!");
                        WaitDialog.show("登录中...");
                        Beans beansIn = new Beans();
                        beansIn.getJsonObject().put("name", "login");
                        beansIn.getJsonObject()
                                .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                                        .getString("phone"));
                        beansIn.getJsonObject()
                                .put("ip", Tools.getIPAddress(MainActivity.getInstance()));
                        beansIn.getJsonObject().put("deviceId", Tools.getUUID());

                        AppParams.getNewNetWork()
                                .setInterface(new NetWorkInterface() {

                                    @Override
                                    public int success(String msg) {
                                        requireActivity().runOnUiThread(new Runnable() {
                                            @RequiresApi(api = Build.VERSION_CODES.O)
                                            @Override
                                            public void run() {
                                                try {
                                                    JSONObject msgFromServer = JSON.parseObject(msg);
                                                    if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                        PopTip.show("登录成功!");
                                                        AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                .putAll(JSON.parseObject(msgFromServer.getString("params")));
                                                        AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                .put("Flag", 1);
                                                        UserMainProfile.uploadSuccessFlag = -1;
                                                        String currentuser = new String(Base64.getEncoder()
                                                                .encode((AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                        .getString("phone") + "#" + AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                        .getString("userid") + "#" + Tools.getSDF()
                                                                        .format(System.currentTimeMillis()) + "#" + AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                        .getString("token")).getBytes()));
                                                        currentuser += "." + MD5Util.string2MD5(currentuser + MD5Keys.getInstance()
                                                                .getKey());
                                                        File f = new File(AppParams.getInstance().mediaDir, "currentuser.txt");
                                                        if (!f.exists()) {
                                                            f.createNewFile();
                                                        }
                                                        FileWriter fileWriter = new FileWriter(f.getAbsoluteFile(), false);
                                                        fileWriter.write(currentuser);
                                                        fileWriter.close();

                                                        f = new File(AppParams.getInstance().mediaDir, "keyParams.txt");
                                                        if (f.exists()) {
                                                            f.delete();
                                                        }

                                                        Message message = new Message();
                                                        message.what = 1;
                                                        HomeMain homeMain = (HomeMain) AppParams.getInstance().sysfragmentmanager.findFragmentByTag("HomeMain");
                                                        if (homeMain != null) {
                                                            homeMain.handler.sendMessage(message);
                                                        }

                                                        SysManagerFragments.switchOnSysFragmentThree("HomeMain");
                                                        WaitDialog.dismiss();

                                                    }
                                                } catch (Throwable e) {
                                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                }
                                            }
                                        });
                                        return 0;
                                    }

                                    @Override
                                    public int failed(String msg) {
                                        return 0;
                                    }
                                })
                                .execute(AppParams.getInstance().baseUrl + "/login", beansIn.getJsonObject()
                                        .toJSONString());
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
                case 3:
                    PopTip.show("获取验证码成功!");
                    CaptchaTimer.captchaTime = 60;
                    break;
                case 4:
                    try {
                        PopTip.show("验证成功!");
                        WaitDialog.show("更改中...");
                        Beans beansIn = new Beans();
                        beansIn.getJsonObject()
                                .put("oldPhone", AppParams.getInstance().appRunParams.getJsonObject()
                                        .getString("oldPhone"));
                        beansIn.getJsonObject()
                                .put("newPhone", AppParams.getInstance().appRunParams.getJsonObject()
                                        .getString("newPhone"));
                        beansIn.getJsonObject()
                                .put("verifyWay", AppParams.getInstance().appRunParams.getJsonObject()
                                        .getIntValue("verifyWay"));
                        beansIn.getJsonObject()
                                .put("answer", AppParams.getInstance().appRunParams.getJsonObject()
                                        .getString("answer"));
                        beansIn.getJsonObject()
                                .put("cardNo", AppParams.getInstance().appRunParams.getJsonObject()
                                        .getString("cardNo"));

                        AppParams.getNewNetWork()
                                .setInterface(new NetWorkInterface() {
                                    @Override
                                    public int success(String msg) {
                                        requireActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    JSONObject msgFromServer = JSON.parseObject(msg);
                                                    if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                        PopTip.show("更换成功，请使用新手机号登录！");
                                                        mHomeLoginPage1.setVisibility(View.VISIBLE);
                                                        mHomeLoginPage2.setVisibility(View.GONE);
                                                        mHomeLoginPage3.setVisibility(View.GONE);
                                                    }
                                                } catch (Throwable e) {
                                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                }
                                            }
                                        });
                                        return 0;
                                    }

                                    @Override
                                    public int failed(String msg) {
                                        requireActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    JSONObject msgFromServer = JSON.parseObject(msg);
                                                    if (Objects.equals(msgFromServer.getString("result"), "失败")) {
                                                        PopTip.show(msgFromServer.getString("msg"));
                                                    }
                                                } catch (Throwable e) {
                                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                }
                                            }
                                        });
                                        return 0;
                                    }
                                })
                                .execute(AppParams.getInstance().baseUrl + "/login/changePhone", beansIn.getJsonObject()
                                        .toJSONString());
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public HomeLogin() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeLogin.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeLogin newInstance(String param1, String param2) {
        HomeLogin fragment = new HomeLogin();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_home_login, container, false);
        initView();
        return rootView;
    }

    private void initView() {

        mHomeLoginPage1 = rootView.findViewById(R.id.home_login_page1);
        mHomeLoginPage1Phone = rootView.findViewById(R.id.home_login_page1_phone);
        mHomeLoginPage1GetCaptcha = rootView.findViewById(R.id.home_login_page1_get_captcha);
        mHomeLoginPage1PhoneNouse = rootView.findViewById(R.id.home_login_page1_phone_nouse);
        mHomeLoginPage1Checkbox = rootView.findViewById(R.id.home_login_page1_checkbox);
        mHomeLoginPage1Protocol = rootView.findViewById(R.id.home_login_page1_protocol);
        mHomeLoginPage1Policy = rootView.findViewById(R.id.home_login_page1_policy);
        mHomeLoginPage2 = rootView.findViewById(R.id.home_login_page2);
        mHomeLoginPage2Iv = rootView.findViewById(R.id.home_login_page2_iv);
        mHomeLoginPage2Captcha = rootView.findViewById(R.id.home_login_page2_captcha);
        mHomeLoginPage2CaptchaGetCaptchaNew = rootView.findViewById(R.id.home_login_page2_captcha_get_captcha_new);
        mHomeLoginPage3 = rootView.findViewById(R.id.home_login_page3);
        mHomeLoginPage3Iv = rootView.findViewById(R.id.home_login_page3_iv);
        mHomeLoginPage3RadioGroup = rootView.findViewById(R.id.home_login_page3_radio_group);
        mHomeLoginPage3RadioGroupBtn1 = rootView.findViewById(R.id.home_login_page3_radio_group_btn_1);
        mHomeLoginPage3RadioGroupBtn2 = rootView.findViewById(R.id.home_login_page3_radio_group_btn_2);
        mHomeLoginPage3WaySelect = rootView.findViewById(R.id.home_login_page3_way_select);
        mHomeLoginPage3Way1 = rootView.findViewById(R.id.home_login_page3_way_1);
        mHomeLoginPage3Way1Question = rootView.findViewById(R.id.home_login_page3_way_1_question);
        mHomeLoginPage3Way1Answer = rootView.findViewById(R.id.home_login_page3_way_1_answer);
        mHomeLoginPage3Way2 = rootView.findViewById(R.id.home_login_page3_way_2);
        mHomeLoginPage3WayCardNo = rootView.findViewById(R.id.home_login_page3_way_card_no);
        mHomeLoginPage3OriginPhone = rootView.findViewById(R.id.home_login_page3_origin_phone);
        mHomeLoginPage3Phone = rootView.findViewById(R.id.home_login_page3_phone);
        mHomeLoginPage3Captcha = rootView.findViewById(R.id.home_login_page3_captcha);
        mHomeLoginPage3GetCaptcha = rootView.findViewById(R.id.home_login_page3_get_captcha);
        mHomeLoginPage3Submit = rootView.findViewById(R.id.home_login_page3_submit);

        mHomeLoginPage3Way1Answer.addTextChangedListener(new CustomLimitInputTextWatcher(mHomeLoginPage3Way1Answer));
        mHomeLoginPage3RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.home_login_page3_radio_group_btn_1) {
                    mHomeLoginPage3Way1.setVisibility(View.VISIBLE);
                    mHomeLoginPage3Way2.setVisibility(View.GONE);
                    verifyWay = 0;
                }
                else if (checkedId == R.id.home_login_page3_radio_group_btn_2) {
                    mHomeLoginPage3Way1.setVisibility(View.GONE);
                    mHomeLoginPage3Way2.setVisibility(View.VISIBLE);
                    verifyWay = 1;
                }
            }
        });
        mHomeLoginPage3Submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    if (!Tools.Deshak()) return;
                    if (mHomeLoginPage3Captcha.getText().toString().isEmpty()) {
                        PopTip.show("验证码为空!");
                        return;
                    }
                    if (CaptchaTimer.getCaptchaSuccess == 0) {
                        PopTip.show("未获取验证码");
                    }
                    else {
                        CaptchaTimer.captchaView = "HomeLoginForPage3";
                        SMSSDK.submitVerificationCode("86", AppParams.getInstance().appRunParams.getJsonObject()
                                .getString("newPhone"), mHomeLoginPage3Captcha.getText()
                                .toString());
                    }

                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mHomeLoginPage3OriginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 11) {
                    try {
                        Beans beansIn = new Beans();
                        beansIn.getJsonObject().put("phone", s.toString());
                        AppParams.getNewNetWork()
                                .setInterface(new NetWorkInterface() {
                                    @Override
                                    public int success(String msg) {
                                        requireActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    JSONObject msgFromServer = JSON.parseObject(msg);
                                                    if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                        mHomeLoginPage3WaySelect.setVisibility(View.VISIBLE);
                                                        mHomeLoginPage3Phone.setVisibility(View.VISIBLE);
                                                        mHomeLoginPage3GetCaptcha.setVisibility(View.VISIBLE);
                                                        mHomeLoginPage3Captcha.setVisibility(View.VISIBLE);
                                                        mHomeLoginPage3Submit.setVisibility(View.VISIBLE);

                                                        if (!StringUtils.isEmpty(msgFromServer.getString("question"))) {
                                                            mHomeLoginPage3Way1.setVisibility(View.VISIBLE);
                                                            verifyWay = 0;
                                                            mHomeLoginPage3RadioGroupBtn1.setChecked(true);
                                                            mHomeLoginPage3Way1Question.setText(msgFromServer.getString("question"));
                                                        }
                                                        else {
                                                            PopTip.show("未设置问题，请选择其他验证方式");
                                                        }


                                                    }
                                                } catch (Throwable e) {
                                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                }
                                            }
                                        });
                                        return 0;
                                    }

                                    @Override
                                    public int failed(String msg) {
                                        requireActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    JSONObject msgFromServer = JSON.parseObject(msg);
                                                    if (Objects.equals(msgFromServer.getString("result"), "失败")) {
                                                        PopTip.show(msgFromServer.getString("msg"));
                                                    }
                                                } catch (Throwable e) {
                                                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                }
                                            }
                                        });
                                        return 0;
                                    }
                                })
                                .execute(AppParams.getInstance().baseUrl + "/login/getChangeState", beansIn.getJsonObject()
                                        .toJSONString());


                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                else {
                    mHomeLoginPage3WaySelect.setVisibility(View.GONE);
                    mHomeLoginPage3Phone.setVisibility(View.GONE);
                    mHomeLoginPage3GetCaptcha.setVisibility(View.GONE);
                    mHomeLoginPage3Captcha.setVisibility(View.GONE);
                    mHomeLoginPage3Submit.setVisibility(View.GONE);

                }
            }
        });
        mHomeLoginPage3GetCaptcha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;
                    if (verifyWay == 0) {
                        if (mHomeLoginPage3Way1Answer.getText().toString().isEmpty()) {
                            PopTip.show("答案为空!");
                            return;
                        }
                    }
                    else if (verifyWay == 1) {
                        if (mHomeLoginPage3WayCardNo.getText().toString().isEmpty()) {
                            PopTip.show("身份证为空!");
                            return;
                        }
                        if (!RegExUtil.isCardNo(mHomeLoginPage3WayCardNo.getText().toString())) {
                            PopTip.show("身份证格式不正确!");
                            return;
                        }

                    }

                    if (mHomeLoginPage3OriginPhone.getText().toString().isEmpty()) {
                        PopTip.show("原手机号为空!");
                        return;
                    }
                    if (!RegExUtil.isPhoneNumber(mHomeLoginPage3OriginPhone.getText().toString())) {
                        PopTip.show("手机号格式不正确!");
                        return;
                    }

                    if (mHomeLoginPage3Phone.getText().toString().isEmpty()) {
                        PopTip.show("新手机号为空!");
                        return;
                    }
                    if (!RegExUtil.isPhoneNumber(mHomeLoginPage3Phone.getText().toString())) {
                        PopTip.show("手机号格式不正确!");
                        return;
                    }
                    if (mHomeLoginPage3OriginPhone.getText()
                            .toString()
                            .equals(mHomeLoginPage3Phone.getText().toString())) {
                        PopTip.show("新手机号和原手机号不能相同!");
                        return;
                    }

                    if (CaptchaTimer.getCaptchaSuccess == 1 && CaptchaTimer.captchaTime < 0) {
                        PopTip.show("请求中...");
                        CaptchaTimer.getCaptchaSuccess = 0;
                        CaptchaTimer.captchaView = "HomeLoginForPage3";
                        AppParams.getInstance().appRunParams.getJsonObject()
                                .put("verifyWay", verifyWay);
                        if (verifyWay == 0) {
                            AppParams.getInstance().appRunParams.getJsonObject()
                                    .put("answer", mHomeLoginPage3Way1Answer.getText().toString());

                        }
                        else if (verifyWay == 1) {
                            AppParams.getInstance().appRunParams.getJsonObject()
                                    .put("cardNo", mHomeLoginPage3WayCardNo.getText().toString());
                        }
                        AppParams.getInstance().appRunParams.getJsonObject()
                                .put("oldPhone", mHomeLoginPage3OriginPhone.getText().toString());
                        AppParams.getInstance().appRunParams.getJsonObject()
                                .put("newPhone", mHomeLoginPage3Phone.getText().toString());
                        SMSSDK.getVerificationCode("86", mHomeLoginPage3Phone.getText().toString());
                    }
                    else {
                        if (CaptchaTimer.captchaTime > 0) {
                            PopTip.show("操作频繁," + CaptchaTimer.captchaTime + "s后再试");
                        }
                        else PopTip.show("操作频繁!");
                    }
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mHomeLoginPage2Iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHomeLoginPage1.setVisibility(View.VISIBLE);
                mHomeLoginPage2.setVisibility(View.GONE);
            }
        });
        mHomeLoginPage1GetCaptcha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;
                    KeyboardsUtils.hintKeyBoards(v);
                    if (!RegExUtil.isPhoneNumber(mHomeLoginPage1Phone.getText().toString())) {
                        PopTip.show("手机号格式不正确!");
                        return;
                    }
                    if (!mHomeLoginPage1Checkbox.isChecked()) {
                        PopTip.show("请先同意用户协议和隐私政策!");
                        return;
                    }
                    if (AppParams.getInstance().vipTest == 1 && (mHomeLoginPage1Phone.getText()
                            .toString()
                            .equals("17310846660") || mHomeLoginPage1Phone.getText()
                            .toString()
                            .equals("13651178942") || mHomeLoginPage1Phone.getText()
                            .toString()
                            .equals("19812109586") || mHomeLoginPage1Phone.getText()
                            .toString()
                            .equals("13888888888"))) {
                        try {
                            AppParams.getInstance().appCurrentUser.getJsonObject()
                                    .put("phone", mHomeLoginPage1Phone.getText().toString());

                            PopTip.show("验证成功!");
                            WaitDialog.show("登录中...");
                            Beans beansIn = new Beans();
                            beansIn.getJsonObject().put("name", "login");
                            beansIn.getJsonObject()
                                    .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                                            .getString("phone"));
                            beansIn.getJsonObject()
                                    .put("ip", Tools.getIPAddress(MainActivity.getInstance()));
                            beansIn.getJsonObject().put("deviceId", Tools.getUUID());


                            AppParams.getNewNetWork()
                                    .setInterface(new NetWorkInterface() {

                                        @Override
                                        public int success(String msg) {
                                            requireActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        JSONObject msgFromServer = JSON.parseObject(msg);
                                                        if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                                            PopTip.show("登录成功!");
                                                            AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                    .putAll(JSON.parseObject(msgFromServer.getString("params")));
                                                            AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                    .put("Flag", 1);
                                                            UserMainProfile.uploadSuccessFlag = -1;
                                                            String currentuser = new String(Base64.getEncoder()
                                                                    .encode((AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                            .getString("phone") + "#" + AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                            .getString("userid") + "#" + Tools.getSDF()
                                                                            .format(System.currentTimeMillis()) + "#" + AppParams.getInstance().appCurrentUser.getJsonObject()
                                                                            .getString("token")).getBytes()));
                                                            currentuser += "." + MD5Util.string2MD5(currentuser + MD5Keys.getInstance()
                                                                    .getKey());
                                                            File f = new File(AppParams.getInstance().mediaDir, "currentuser.txt");
                                                            FileWriter fileWriter = new FileWriter(f.getAbsoluteFile(), false);
                                                            fileWriter.write(currentuser);
                                                            fileWriter.close();


                                                            f = new File(AppParams.getInstance().mediaDir, "keyParams.txt");
                                                            if (f.exists()) {
                                                                f.delete();
                                                            }

                                                            Message message = new Message();
                                                            message.what = 1;
                                                            HomeMain homeMain = (HomeMain) AppParams.getInstance().sysfragmentmanager.findFragmentByTag("HomeMain");
                                                            if (homeMain != null) {
                                                                homeMain.handler.sendMessage(message);
                                                                homeMain.handler.postDelayed(new Runnable() {
                                                                    @Override
                                                                    public void run() {
                                                                        SysManagerFragments.switchOnSysFragmentThree("HomeMain");

                                                                    }
                                                                }, 200);
                                                            }


                                                            WaitDialog.dismiss();
                                                        }
                                                    } catch (Throwable e) {
                                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                                    }
                                                }
                                            });
                                            return 0;
                                        }

                                        @Override
                                        public int failed(String msg) {
                                            return 0;
                                        }
                                    })
                                    .execute(AppParams.getInstance().baseUrl + "/login", beansIn.getJsonObject()
                                            .toJSONString());
                        } catch (Throwable e) {
                            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                        }
                    }
                    else if (CaptchaTimer.getCaptchaSuccess == 1 && CaptchaTimer.captchaTime < 0) {
                        PopTip.show("请求中...");
                        CaptchaTimer.getCaptchaSuccess = 0;
                        CaptchaTimer.captchaView = "HomeLoginForPage1";
                        AppParams.getInstance().appCurrentUser.getJsonObject()
                                .put("phone", mHomeLoginPage1Phone.getText().toString());
                        SMSSDK.getVerificationCode("86", mHomeLoginPage1Phone.getText().toString());
                    }
                    else {
                        if (CaptchaTimer.captchaTime > 0) {
                            PopTip.show("操作频繁," + CaptchaTimer.captchaTime + "s后再试");
                        }
                        else PopTip.show("操作频繁!");
                    }
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mHomeLoginPage2CaptchaGetCaptchaNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (CaptchaTimer.getCaptchaSuccess == 1 && CaptchaTimer.captchaTime < 0) {
                        PopTip.show("请求中...");
                        CaptchaTimer.getCaptchaSuccess = 0;
                        CaptchaTimer.captchaView = "HomeLoginForPage1";
                        AppParams.getInstance().appCurrentUser.getJsonObject()
                                .put("phone", mHomeLoginPage1Phone.getText().toString());
                        SMSSDK.getVerificationCode("86", mHomeLoginPage1Phone.getText().toString());
                    }
                    else {
                        if (CaptchaTimer.captchaTime > 0) {
                            PopTip.show("操作频繁," + CaptchaTimer.captchaTime + "s后再试");
                        }
                        else PopTip.show("操作频繁!");
                    }
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mHomeLoginPage2Captcha.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 6) {
                    try {
                        if (!Tools.Deshak()) return;
                        WaitDialog.show("请稍后...");
                        if (CaptchaTimer.getCaptchaSuccess == 0) {
                            PopTip.show("未获取验证码");
                        }
                        else {
                            CaptchaTimer.captchaView = "HomeLoginForPage2";
                            SMSSDK.submitVerificationCode("86", AppParams.getInstance().appCurrentUser.getJsonObject()
                                    .getString("phone"), s.toString());
                        }
                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
            }
        });
        mHomeLoginPage1PhoneNouse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;
                    mHomeLoginPage1.setVisibility(View.GONE);
                    mHomeLoginPage3.setVisibility(View.VISIBLE);
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mHomeLoginPage1Protocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;


                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    Uri uri = Uri.parse(AppParams.getInstance().protocolUrl);
                    intent.setData(uri);
                    startActivity(intent);

//                    CustomDialog.show(new OnBindView<CustomDialog>(R.layout.fragment_user_setting_dialog_protocol_policy) {
//                        @Override
//                        public void onBind(final CustomDialog dialog, View v) {
//                            WebView webview = v.findViewById(R.id.dialog_protocol_policy_webview);
//                            webview.loadUrl(AppParams.getInstance().protocolUrl);
//                            webview.setWebViewClient(new WebViewClient());
//                            webview.reload();
//                            TextView textView = v.findViewById(R.id.dialog_protocol_policy_cancel);
//                            textView.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    dialog.dismiss();
//                                }
//                            });
//                        }
//                    });
//
//
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mHomeLoginPage1Policy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;

                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    Uri uri = Uri.parse(AppParams.getInstance().policyUrl);
                    intent.setData(uri);
                    startActivity(intent);

//                    CustomDialog.show(new OnBindView<CustomDialog>(R.layout.fragment_user_setting_dialog_protocol_policy) {
//                        @Override
//                        public void onBind(final CustomDialog dialog, View v) {
//                            WebView webview = v.findViewById(R.id.dialog_protocol_policy_webview);
//                            webview.loadUrl(AppParams.getInstance().policyUrl);
//                            webview.setWebViewClient(new WebViewClient());
//                            webview.reload();
//                            TextView textView = v.findViewById(R.id.dialog_protocol_policy_cancel);
//                            textView.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    dialog.dismiss();
//                                }
//                            });
//                        }
//                    });
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mHomeLoginPage3Iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!Tools.Deshak()) return;
                    mHomeLoginPage1.setVisibility(View.VISIBLE);
                    mHomeLoginPage3.setVisibility(View.GONE);
                    KeyboardsUtils.hintKeyBoards(v);
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
        else {
            if (timer != null) timer.cancel();
        }
    }

    private void initChanged() {
        try {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (CaptchaTimer.captchaTime > 0) {
                                    mHomeLoginPage2CaptchaGetCaptchaNew.setText("重新获取(" + CaptchaTimer.captchaTime + "s)");
                                    mHomeLoginPage3GetCaptcha.setText("重新获取(" + CaptchaTimer.captchaTime + "s)");
                                }
                                else {
                                    mHomeLoginPage2CaptchaGetCaptchaNew.setText("重新获取");
                                    mHomeLoginPage3GetCaptcha.setText("获取验证码");
                                }
                            } catch (Throwable e) {
                                ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                            }
                        }
                    });
                }
            }, 0, 1000);

            mHomeLoginPage1.setVisibility(View.VISIBLE);
            mHomeLoginPage2.setVisibility(View.GONE);

        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}